package homework.util.db;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBEngine {

    private String uri;
    private String user;
    private String pwd;

    public DBEngine(String driver, String uri, String user, String pwd)
            throws ClassNotFoundException {
        Class.forName(driver);
        this.uri = uri;
        this.user = user;
        this.pwd = pwd;
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(uri, user, pwd);
    }

    public boolean execute(String sql) throws SQLException {
        Connection conn = getConnection();
        Statement sm = conn.createStatement();
        boolean b = sm.execute(sql);
        close(conn, sm, null);
        return b;
    }

    public static void close(Connection conn, Statement sm,  ResultSet result) {
        try {
            if(result != null && !result.isClosed())
                result.close();
            if(sm != null && !sm.isClosed())
                sm.close();
            if(conn != null && !conn.isClosed())
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static DBEngine fromPropertiesFile(String path)
            throws IOException, ClassNotFoundException {
        FileInputStream file = new FileInputStream(path);
        return fromPropertiesFile(file);
    }

    public static DBEngine fromPropertiesFile(FileInputStream file)
            throws IOException, ClassNotFoundException {
        Properties prop = new Properties();
        prop.load(file);
        return new DBEngine(prop.getProperty("driver"), prop.getProperty("URI"),
                prop.getProperty("USERNAME"), prop.getProperty("PASSWORD"));
    }
}
